import axios, { AxiosInstance } from "axios";
import { getAccessToken } from "./auth";
import exportVue from "@/assets/modules/exportVue";

const requestServe: any = {
  VIID: "/VIID"
};

const instance: AxiosInstance = axios.create();
instance.defaults.timeout = 3000000;
instance.defaults.withCredentials = false;

instance.interceptors.request.use(
  config => {
    const token = getAccessToken();
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  error => {
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  }
);

instance.interceptors.response.use(
  response => {
    if (response && response.data && response.data.code == "401") {
      exportVue
        .$confirm("您已登录失效, 请前去登录?", "提示!", {
          confirmButtonText: "去登录",
          type: "warning",
          showClose: false,
          showCancelButton: false
        })
        .then(() => {
          const win: any = window;
          window.location.replace(win.user.loginUrl);
        });
    }
    return response;
  },
  error => {
    if (error.response) {
      console.log(error.response);
    } else {
      console.log(error);
    }
  }
);
/**
 * 启动云平台控制
 */
export function startVIID(param: any) {
  return new Promise((resolve, reject) => {
    instance
      .post(`${requestServe.VIID}/start`, param)
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data);
      });
  });
}
/**
 * 释放云平台控制权
 */
export function releaseVIID(param: any) {
  return new Promise((resolve, reject) => {
    instance
      .post(`${requestServe.VIID}/release`, param)
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data);
      });
  });
}
//跨浏览器播放登录
export const VideoUrlLogin = () => {
  return axios({
    method: "POST",
    url: `${requestServe.VIID}/login/v2`,
    headers: {
      "Content-Type": "application/json;charset=UTF-8"
    },
    responseType: "json"
  });
};
//跨浏览器播放登录2
export const VideoUrlLogin2 = (data: any) => {
  return axios({
    method: "POST",
    url: `${requestServe.VIID}/login/v2`,
    headers: {
      "Content-Type": "application/json;charset=UTF-8"
    },
    data
  });
};
//保活
export const keepalive = () => {
  return new Promise((resolve, reject) => {
    instance
      .post(`${requestServe.VIID}/hadesadapter/user/keepalive`, {})
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data);
      });
  });
};
